package com.example.managemyself.ui.settings;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.managemyself.R;
import com.example.managemyself.util.ApiKeyManager;
import com.example.managemyself.util.DeepSeekHelper;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;

/**
 * API密钥设置界面
 */
public class ApiKeySettingsActivity extends AppCompatActivity {
    
    private TextInputLayout tilApiKey;
    private TextInputEditText etApiKey;
    private Button btnSaveApiKey, btnTestApiKey;
    private ProgressBar progressBar;
    private RecyclerView rvApiKeys;
    private FloatingActionButton fabAddKey;
    
    private ApiKeyManager apiKeyManager;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_api_key_settings);
        
        initViews();
        setupToolbar();
        setupListeners();
        
        apiKeyManager = ApiKeyManager.getInstance(this);
        loadExistingApiKeys();
    }
    
    private void initViews() {
        tilApiKey = findViewById(R.id.tilApiKey);
        etApiKey = findViewById(R.id.etApiKey);
        btnSaveApiKey = findViewById(R.id.btnSaveApiKey);
        btnTestApiKey = findViewById(R.id.btnTestApiKey);
        progressBar = findViewById(R.id.progressBar);
        rvApiKeys = findViewById(R.id.rvApiKeys);
        fabAddKey = findViewById(R.id.fabAddKey);
    }
    
    private void setupToolbar() {
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setTitle("API密钥管理");
        }
    }
    
    private void setupListeners() {
        btnSaveApiKey.setOnClickListener(v -> saveApiKey());
        btnTestApiKey.setOnClickListener(v -> testApiKey());
        fabAddKey.setOnClickListener(v -> showAddApiKeyDialog());
    }
    
    private void loadExistingApiKeys() {
        // 加载现有的DeepSeek API密钥
        apiKeyManager.getDeepSeekApiKey(apiKey -> {
            runOnUiThread(() -> {
                if (apiKey != null && !apiKey.isEmpty()) {
                    // 显示部分密钥（保护隐私）
                    String maskedKey = maskApiKey(apiKey);
                    etApiKey.setText(maskedKey);
                    etApiKey.setEnabled(false);
                    btnSaveApiKey.setText("更新密钥");
                } else {
                    etApiKey.setHint("请输入您的DeepSeek API密钥");
                }
            });
        });
    }
    
    private String maskApiKey(String apiKey) {
        if (apiKey == null || apiKey.length() < 8) {
            return apiKey;
        }
        String prefix = apiKey.substring(0, 6);
        String suffix = apiKey.substring(apiKey.length() - 4);
        return prefix + "****" + suffix;
    }
    
    private void saveApiKey() {
        String apiKey = etApiKey.getText().toString().trim();
        
        if (TextUtils.isEmpty(apiKey)) {
            tilApiKey.setError("请输入API密钥");
            return;
        }
        
        if (apiKey.contains("****")) {
            // 如果是掩码显示，则显示更新对话框
            showUpdateApiKeyDialog();
            return;
        }
        
        if (!isValidDeepSeekApiKey(apiKey)) {
            tilApiKey.setError("API密钥格式不正确");
            return;
        }
        
        tilApiKey.setError(null);
        progressBar.setVisibility(View.VISIBLE);
        btnSaveApiKey.setEnabled(false);
        
        apiKeyManager.saveApiKey(
            ApiKeyManager.API_TYPE_DEEPSEEK,
            apiKey,
            "DeepSeek API",
            new ApiKeyManager.SaveCallback() {
                @Override
                public void onSuccess(String message) {
                    runOnUiThread(() -> {
                        progressBar.setVisibility(View.GONE);
                        btnSaveApiKey.setEnabled(true);
                        Toast.makeText(ApiKeySettingsActivity.this, message, Toast.LENGTH_SHORT).show();
                        loadExistingApiKeys(); // 重新加载以显示掩码
                    });
                }
                
                @Override
                public void onError(String error) {
                    runOnUiThread(() -> {
                        progressBar.setVisibility(View.GONE);
                        btnSaveApiKey.setEnabled(true);
                        Toast.makeText(ApiKeySettingsActivity.this, error, Toast.LENGTH_LONG).show();
                    });
                }
            }
        );
    }
    
    private void testApiKey() {
        String apiKey = etApiKey.getText().toString().trim();
        
        if (TextUtils.isEmpty(apiKey) || apiKey.contains("****")) {
            // 如果是掩码或空，使用数据库中的密钥测试
            testStoredApiKey();
            return;
        }
        
        if (!isValidDeepSeekApiKey(apiKey)) {
            Toast.makeText(this, "API密钥格式不正确", Toast.LENGTH_SHORT).show();
            return;
        }
        
        progressBar.setVisibility(View.VISIBLE);
        btnTestApiKey.setEnabled(false);
        
        // 临时测试API密钥
        testApiKeyWithMessage(apiKey, "你好，这是一个API连接测试。");
    }
    
    private void testStoredApiKey() {
        progressBar.setVisibility(View.VISIBLE);
        btnTestApiKey.setEnabled(false);
        
        // 使用DeepSeekHelper测试（它会自动使用数据库中的密钥）
        DeepSeekHelper.getChatResponse("你好，这是一个API连接测试。", new DeepSeekHelper.DeepSeekCallback() {
            @Override
            public void onResponse(String response) {
                runOnUiThread(() -> {
                    progressBar.setVisibility(View.GONE);
                    btnTestApiKey.setEnabled(true);
                    showTestResultDialog("测试成功", "API连接正常！\n\n响应: " + response);
                });
            }
            
            @Override
            public void onError(String error) {
                runOnUiThread(() -> {
                    progressBar.setVisibility(View.GONE);
                    btnTestApiKey.setEnabled(true);
                    showTestResultDialog("测试失败", "API连接失败: " + error);
                });
            }
        });
    }
    
    private void testApiKeyWithMessage(String apiKey, String testMessage) {
        // 这里需要临时使用提供的API密钥进行测试
        // 由于DeepSeekHelper现在使用数据库，我们需要先临时保存，测试后再决定是否保留
        Toast.makeText(this, "请先保存API密钥，然后进行测试", Toast.LENGTH_SHORT).show();
        progressBar.setVisibility(View.GONE);
        btnTestApiKey.setEnabled(true);
    }
    
    private void showTestResultDialog(String title, String message) {
        new AlertDialog.Builder(this)
                .setTitle(title)
                .setMessage(message)
                .setPositiveButton("确定", null)
                .show();
    }
    
    private void showUpdateApiKeyDialog() {
        final EditText etNewApiKey = new EditText(this);
        etNewApiKey.setHint("请输入新的DeepSeek API密钥");
        etNewApiKey.setInputType(android.text.InputType.TYPE_TEXT_VARIATION_PASSWORD);
        
        new AlertDialog.Builder(this)
                .setTitle("更新API密钥")
                .setMessage("请输入新的DeepSeek API密钥")
                .setView(etNewApiKey)
                .setPositiveButton("更新", (dialog, which) -> {
                    String newApiKey = etNewApiKey.getText().toString().trim();
                    if (!TextUtils.isEmpty(newApiKey) && isValidDeepSeekApiKey(newApiKey)) {
                        etApiKey.setText(newApiKey);
                        etApiKey.setEnabled(true);
                        saveApiKey();
                    } else {
                        Toast.makeText(this, "API密钥格式不正确", Toast.LENGTH_SHORT).show();
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }
    
    private void showAddApiKeyDialog() {
        final EditText etApiKey = new EditText(this);
        etApiKey.setHint("请输入DeepSeek API密钥");
        etApiKey.setInputType(android.text.InputType.TYPE_TEXT_VARIATION_PASSWORD);
        
        new AlertDialog.Builder(this)
                .setTitle("添加API密钥")
                .setView(etApiKey)
                .setPositiveButton("添加", (dialog, which) -> {
                    String apiKey = etApiKey.getText().toString().trim();
                    
                    if (TextUtils.isEmpty(apiKey)) {
                        Toast.makeText(this, "请输入API密钥", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    
                    if (isValidDeepSeekApiKey(apiKey)) {
                        apiKeyManager.saveApiKey(
                            ApiKeyManager.API_TYPE_DEEPSEEK,
                            apiKey,
                            "DeepSeek API",
                            new ApiKeyManager.SaveCallback() {
                                @Override
                                public void onSuccess(String message) {
                                    runOnUiThread(() -> {
                                        Toast.makeText(ApiKeySettingsActivity.this, message, Toast.LENGTH_SHORT).show();
                                        loadExistingApiKeys();
                                    });
                                }
                                
                                @Override
                                public void onError(String error) {
                                    runOnUiThread(() -> {
                                        Toast.makeText(ApiKeySettingsActivity.this, error, Toast.LENGTH_LONG).show();
                                    });
                                }
                            }
                        );
                    } else {
                        Toast.makeText(this, "API密钥格式不正确", Toast.LENGTH_SHORT).show();
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }
    
    private boolean isValidDeepSeekApiKey(String apiKey) {
        // DeepSeek API密钥通常以sk-开头
        return apiKey != null && apiKey.startsWith("sk-") && apiKey.length() > 10;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            onBackPressed();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
} 